;((doc, Socket, storage, location)=> {
  const oList = doc.querySelector('#list');
  const oMsg = doc.querySelector('#message');
  const oSend = doc.querySelector('#send');

  let username = '';

  const ws = new Socket('ws:localhost:8000')

  const init = () => {
    bindEvent()
  }

  function bindEvent() {
    oSend.addEventListener('click', handleSendBtnClick, false);

    ws.addEventListener('open', handleOpen, false);
    ws.addEventListener('close', handleClose, false);
    ws.addEventListener('error', handleError, false);
    ws.addEventListener('message', handleMessage, false);
  }

  function handleSendBtnClick() {
    console.log('send message');

    const msg = oMsg.value;

    if(!msg.trim().length) {
      return;
    }

    console.log(JSON.stringify({
      user: username,
      dateTime: new Date().getTime(),
      message: msg
    }));
    ws.send(JSON.stringify({
      username: username,
      dateTime: new Date().getTime(),
      message: msg
    }));

    oMsg.value = '';
  }

  function handleOpen(e) {
    console.log('websocket open', e);

    username = storage.getItem('username');

    console.log(username);
    if(!username) {
      location.href = 'entry.html';
      return;
    }
  }

  function handleClose(e) {
    console.log('websocket close', e);
  }

  function handleError(e) {
    console.log('websocket error', e);
  }

  function handleMessage(e) {
    console.log('websocket message', e);
    const msgData = JSON.parse(e.data) ;
    oList.appendChild(createMsg(msgData));
  }

  function createMsg(data) {
    const { user, dateTime, message } = data;
    const oItem = doc.createElement('li');
    oItem.innerHTML = `
    <span>${ username }</span>
    <span>${ dateTime }</span>
    <p>信息：${ message }</p>
    `;

    return oItem;
  }

  init()
})(document, WebSocket, localStorage, location)